// 导入工具函数
const { checkDirectoryExistsSync, moveFileToTargetSync } = require('../utils')
// 导入数据库操作函数
const { initSqlite3DB, insertData, querybyname, updatepath } = require('../db')

// 导入 uuid 生成器
const { v4: uuidv4 } = require('uuid')

const path = require('path')
const fs = require('fs')

const db_path = path.join(process.cwd(), 'db/projectinfo.db')

// 1. 判断 classid 对应目录是否存在
const checkClassDir = async (ctx, netx) => {
    const { classId } = ctx.request.body

    // 拼接上传文件存储目录
    const classDir = path.join(process.cwd(), 'uploads', classId)
    ctx.state.classDir = classDir

    // 判断 classDir 目录是否存在
    if (!checkDirectoryExistsSync(classDir)) {
        ctx.body = {
            code: 404,
            message: `${classId} 班暂未开放项目提交权限`
        }
        return
    }

    netx()
}


// 2. 判断用户是否已经上传文件
const checkUserFile = async (ctx, netx) => {
    const { classId, studentName } = ctx.request.body

    // 创建数据库连接
    const db =  initSqlite3DB(db_path)
    const result = querybyname(db, { classid: classId, name: studentName })

    if (result.length > 0) {
        ctx.state.old_path = result[0].path
    }
    db.close()
    netx()
}

// 3. 保存上传文件
const saveFile = async (ctx, netx) => {
    const file = ctx.request.files.file

    const { classId, studentId, studentName, projectName, skillType } = ctx.request.body

    // 拼接得到最新上传文件名
    const extname = file.originalFilename.split('.').pop()
    const project_file_name = studentId + "-" + studentName + "-" + projectName + "（"+ skillType + "）." + extname
    const new_path = path.join(ctx.state.classDir, project_file_name)

    // 创建数据库连接
    const db =  initSqlite3DB(db_path)

    let operation_result = null

    if (ctx.state.old_path) {
        // 删除原有文件
        fs.unlinkSync(ctx.state.old_path)

        // 更新数据库中文件路径
        operation_result = updatepath(db, { classid: classId, name: studentName, projectname: projectName, skilltype: skillType, path: new_path })
    } else {
        // 新增数据到数据库
        data = {
            classid: classId,
            name: studentName,
            projectname: projectName,
            projectid: uuidv4(),
            path: new_path,
            skilltype: skillType
        }

        operation_result = insertData(db, data) // 插入数据库记录
    }

    // 保存上传文件
    const is_saved = moveFileToTargetSync(file.filepath, new_path)
    if (operation_result && is_saved) {
        ctx.body = {
            code: 200,
            message: '文件上传成功'
        }
    } else {
        ctx.body = {
            code: 500,
            message: '文件上传失败'
        }
    }

    db.close()
    return

}

// 导出
module.exports = {
    checkClassDir,
    checkUserFile,
    saveFile
}